<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAdminStore } from '@/store/admin'
import { useAuthStore } from '@/store/auth'

const router = useRouter()
const adminStore = useAdminStore()
const authStore = useAuthStore()

const dashboardData = ref({
  userStats: {
    total: 0,
    newToday: 0,
    newThisWeek: 0,
    active: 0
  },
  blogStats: {
    total: 0,
    published: 0,
    draft: 0,
    archived: 0,
    newToday: 0
  },
  commentStats: {
    total: 0,
    pending: 0,
    newToday: 0
  },
  typeStats: {
    total: 0,
    mostUsed: null
  },
  recentActivities: []
})

const loading = ref(true)
const chartData = ref(null)
const userCountByDay = ref([])
const blogCountByDay = ref([])
const viewsCountByDay = ref([])

// 统计图配置
const chartOptions = computed(() => ({
  responsive: true,
  maintainAspectRatio: false,
  scales: {
    y: {
      beginAtZero: true
    }
  },
  interaction: {
    intersect: false
  },
  plugins: {
    legend: {
      position: 'top'
    },
    tooltip: {
      mode: 'index'
    }
  }
}))

onMounted(async () => {
  if (!authStore.isAuthenticated || !authStore.isAdmin) {
    router.push('/login')
    return
  }
  
  try {
    loading.value = true
    
    // 获取仪表盘数据
    const data = await adminStore.fetchDashboardData()
    dashboardData.value = data
    
    // 获取统计图数据
    const stats = await adminStore.fetchStatisticsData()
    userCountByDay.value = stats.userCountByDay || []
    blogCountByDay.value = stats.blogCountByDay || []
    viewsCountByDay.value = stats.viewsCountByDay || []
    
    // 准备图表数据
    prepareChartData()
  } catch (error) {
    console.error('Failed to load dashboard data:', error)
  } finally {
    loading.value = false
  }
})

const prepareChartData = () => {
  const labels = userCountByDay.value.map(item => item.date).slice(-7)
  
  chartData.value = {
    labels,
    datasets: [
      {
        label: '新增用户',
        data: userCountByDay.value.map(item => item.count).slice(-7),
        backgroundColor: 'rgba(74, 111, 165, 0.2)',
        borderColor: 'rgba(74, 111, 165, 1)',
        borderWidth: 2,
        tension: 0.4
      },
      {
        label: '新增博客',
        data: blogCountByDay.value.map(item => item.count).slice(-7),
        backgroundColor: 'rgba(217, 100, 43, 0.2)',
        borderColor: 'rgba(217, 100, 43, 1)',
        borderWidth: 2,
        tension: 0.4
      },
      {
        label: '浏览量',
        data: viewsCountByDay.value.map(item => item.count).slice(-7),
        backgroundColor: 'rgba(110, 139, 176, 0.2)',
        borderColor: 'rgba(110, 139, 176, 1)',
        borderWidth: 2,
        tension: 0.4
      }
    ]
  }
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getActivityIcon = (type) => {
  const icons = {
    user_register: '👤',
    user_login: '🔑',
    blog_create: '📝',
    blog_update: '✏️',
    blog_delete: '🗑️',
    comment_create: '💬',
    comment_delete: '🗑️',
    type_create: '🏷️',
    type_update: '🔄',
    type_delete: '❌'
  }
  return icons[type] || '📋'
}

const getActivityText = (activity) => {
  const actionMap = {
    user_register: '注册了账号',
    user_login: '登录了系统',
    blog_create: '创建了博客',
    blog_update: '更新了博客',
    blog_delete: '删除了博客',
    comment_create: '发表了评论',
    comment_delete: '删除了评论',
    type_create: '创建了分类',
    type_update: '更新了分类',
    type_delete: '删除了分类'
  }
  
  return `${activity.username || '用户'} ${actionMap[activity.type] || '进行了操作'}`
}

const navigateToUsers = () => {
  router.push('/admin/users')
}

const navigateToBlogs = () => {
  router.push('/admin/blogs')
}

const navigateToComments = () => {
  router.push('/admin/comments')
}

const navigateToBlogTypes = () => {
  router.push('/admin/blog-types')
}
</script>

<template>
  <div class="admin-dashboard">
    <h2 class="page-title">管理员仪表盘</h2>
    
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
    </div>
    
    <template v-else>
      <!-- 概览统计卡片 -->
      <div class="stats-cards">
        <div class="stat-card card" @click="navigateToUsers">
          <div class="stat-icon user-icon">👥</div>
          <div class="stat-content">
            <div class="stat-value">{{ dashboardData.userStats.total }}</div>
            <div class="stat-label">用户总数</div>
            <div class="stat-detail">今日新增: {{ dashboardData.userStats.newToday }}</div>
          </div>
        </div>
        
        <div class="stat-card card" @click="navigateToBlogs">
          <div class="stat-icon blog-icon">📝</div>
          <div class="stat-content">
            <div class="stat-value">{{ dashboardData.blogStats.total }}</div>
            <div class="stat-label">博客总数</div>
            <div class="stat-detail">已发布: {{ dashboardData.blogStats.published }}</div>
          </div>
        </div>
        
        <div class="stat-card card" @click="navigateToComments">
          <div class="stat-icon comment-icon">💬</div>
          <div class="stat-content">
            <div class="stat-value">{{ dashboardData.commentStats.total }}</div>
            <div class="stat-label">评论总数</div>
            <div class="stat-detail">待审核: {{ dashboardData.commentStats.pending }}</div>
          </div>
        </div>
        
        <div class="stat-card card" @click="navigateToBlogTypes">
          <div class="stat-icon type-icon">🏷️</div>
          <div class="stat-content">
            <div class="stat-value">{{ dashboardData.typeStats.total }}</div>
            <div class="stat-label">博客分类</div>
            <div class="stat-detail">最多使用: {{ dashboardData.typeStats.mostUsed || '-' }}</div>
          </div>
        </div>
      </div>
      
      <!-- 详细统计信息 -->
      <div class="dashboard-detailed">
        <!-- 统计图 -->
        <div class="dashboard-chart card">
          <h3 class="card-title">最近7天统计</h3>
          <div class="chart-container">
            <!-- 这里替换为实际的图表组件 -->
            <div class="chart-placeholder">
              <div v-if="chartData" class="chart-mock">
                <div v-for="(dataset, i) in chartData.datasets" :key="i" class="chart-legend-item">
                  <span class="chart-legend-color" :style="{ backgroundColor: dataset.borderColor }"></span>
                  <span class="chart-legend-label">{{ dataset.label }}</span>
                </div>
                <div class="chart-mock-content">图表数据已加载，请集成实际图表组件</div>
              </div>
              <div v-else class="chart-mock-empty">
                暂无图表数据
              </div>
            </div>
          </div>
        </div>
        
        <!-- 最近活动 -->
        <div class="recent-activities card">
          <h3 class="card-title">最近活动</h3>
          
          <div v-if="dashboardData.recentActivities.length === 0" class="no-activities">
            暂无活动记录
          </div>
          
          <div v-else class="activities-list">
            <div 
              v-for="(activity, index) in dashboardData.recentActivities" 
              :key="index" 
              class="activity-item"
            >
              <div class="activity-icon">
                <span>{{ getActivityIcon(activity.type) }}</span>
              </div>
              <div class="activity-content">
                <div class="activity-text">{{ getActivityText(activity) }}</div>
                <div class="activity-time">{{ formatDate(activity.createTime) }}</div>
                <div v-if="activity.details" class="activity-details">
                  {{ activity.details }}
                </div>
              </div>
            </div>
          </div>
          
          <div class="view-all-logs">
            <router-link to="/admin/logs" class="btn btn-secondary btn-sm">
              查看所有日志
            </router-link>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<style>
.admin-dashboard {
  padding: 0.5rem 0;
}

.page-title {
  font-size: 1.75rem;
  font-weight: 600;
  margin-bottom: 1.5rem;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 1.5rem;
  margin-bottom: 1.5rem;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 1.5rem;
  border-radius: 8px;
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 54px;
  height: 54px;
  border-radius: 50%;
  font-size: 1.75rem;
  margin-right: 1rem;
}

.user-icon {
  background-color: rgba(74, 111, 165, 0.2);
  color: var(--primary-color);
}

.blog-icon {
  background-color: rgba(217, 100, 43, 0.2);
  color: var(--accent-color);
}

.comment-icon {
  background-color: rgba(110, 139, 176, 0.2);
  color: var(--secondary-color);
}

.type-icon {
  background-color: rgba(92, 184, 92, 0.2);
  color: var(--success-color);
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 1.75rem;
  font-weight: 600;
  margin-bottom: 0.25rem;
}

.stat-label {
  color: var(--text-light);
  font-size: 0.95rem;
  margin-bottom: 0.25rem;
}

.stat-detail {
  font-size: 0.85rem;
  color: var(--text-light);
}

.dashboard-detailed {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 1.5rem;
}

.dashboard-chart, .recent-activities {
  padding: 1.5rem;
}

.card-title {
  font-size: 1.25rem;
  font-weight: 600;
  margin-bottom: 1.5rem;
  color: var(--primary-color);
}

.chart-container {
  height: 300px;
  width: 100%;
}

.chart-placeholder {
  width: 100%;
  height: 100%;
  background-color: #f8f9fa;
  border: 1px dashed var(--border-color);
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.chart-mock {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 1rem;
}

.chart-legend-item {
  display: flex;
  align-items: center;
  margin-bottom: 0.5rem;
}

.chart-legend-color {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  margin-right: 0.5rem;
}

.chart-mock-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-light);
  border-top: 1px dashed var(--border-color);
  margin-top: 1rem;
  padding-top: 1rem;
}

.chart-mock-empty {
  color: var(--text-light);
}

.activities-list {
  max-height: 350px;
  overflow-y: auto;
}

.activity-item {
  display: flex;
  margin-bottom: 1.5rem;
  padding-bottom: 1.5rem;
  border-bottom: 1px solid var(--border-color);
}

.activity-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.activity-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #f8f9fa;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 1rem;
  font-size: 1.25rem;
}

.activity-content {
  flex: 1;
}

.activity-text {
  font-size: 0.95rem;
  margin-bottom: 0.25rem;
}

.activity-time {
  font-size: 0.85rem;
  color: var(--text-light);
}

.activity-details {
  margin-top: 0.5rem;
  font-size: 0.85rem;
  color: var(--text-light);
  background-color: #f8f9fa;
  padding: 0.5rem;
  border-radius: 4px;
}

.no-activities {
  color: var(--text-light);
  text-align: center;
  padding: 2rem 0;
}

.view-all-logs {
  margin-top: 1.5rem;
  text-align: center;
}

.btn-sm {
  padding: 0.375rem 0.75rem;
  font-size: 0.875rem;
}

@media (max-width: 1200px) {
  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .dashboard-detailed {
    grid-template-columns: 1fr;
  }
  
  .chart-container {
    height: 250px;
  }
}

@media (max-width: 576px) {
  .stats-cards {
    grid-template-columns: 1fr;
  }
}
</style> 